<?php namespace Modules\Shop\Http\Controllers;

class VoteController extends Controller {

    public function getIndex()
    {
        global $_CFG, $ecs, $err, $smarty, $_LANG, $db;

        if (!is_set(\Input::get('vote')) || !is_set(\Input::get('options')) || !is_set(\Input::get('type'))) {
            ecs_header("Location: ./\n");
            exit;
        }

        $res = array('error' => 0, 'message' => '', 'content' => '');

        $vote_id = intval($_POST['vote']);
        $options = trim($_POST['options']);
        $type = intval($_POST['type']);
        $ip_address = real_ip();

        if (vote_already_submited($vote_id, $ip_address)) {
            $res['error'] = 1;
            $res['message'] = $_LANG['vote_ip_same'];
        } else {
            save_vote($vote_id, $ip_address, $options);

            $vote = get_vote($vote_id);
            if (!empty($vote)) {
                \Tpl::assign('vote_id', $vote['id']);
                \Tpl::assign('vote', $vote['content']);
            }

            $str = \Tpl::fetch("library/vote.lbi");

            $pattern = '/(?:<(\w+)[^>]*> .*?)?<div\s+id="ECS_VOTE">(.*)<\/div>(?:.*?<\/\1>)?/is';

            if (preg_match($pattern, $str, $match)) {
                $res['content'] = $match[2];
            }
            $res['message'] = $_LANG['vote_success'];
        }

        $json = new JSON;

        echo $json->encode($res);

        return view('shop::index');
	}
	
}


/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */

/**
 * 检查是否已经提交过投票
 *
 * @access  private
 * @param   integer $vote_id
 * @param   string  $ip_address
 * @return  boolean
 */
function vote_already_submited($vote_id, $ip_address)
{
    $sql = "SELECT COUNT(*) FROM " . \ECS::table('vote_log') . " " .
        "WHERE ip_address = '$ip_address' AND vote_id = '$vote_id' ";

    return (\Ecdb::GetOne($sql) > 0);
}

/**
 * 保存投票结果信息
 *
 * @access  public
 * @param   integer $vote_id
 * @param   string  $ip_address
 * @param   string  $option_id
 * @return  void
 */
function save_vote($vote_id, $ip_address, $option_id)
{
    $sql = "INSERT INTO " . \ECS::table('vote_log') . " (vote_id, ip_address, vote_time) " .
        "VALUES ('$vote_id', '$ip_address', " . gmtime() . ")";
    $res = \Ecdb::query($sql);

    /* 更新投票主题的数量 */
    $sql = "UPDATE " . \ECS::table('vote') . " SET " .
        "vote_count = vote_count + 1 " .
        "WHERE vote_id = '$vote_id'";
    \Ecdb::query($sql);

    /* 更新投票选项的数量 */
    $sql = "UPDATE " . \ECS::table('vote_option') . " SET " .
        "option_count = option_count + 1 " .
        "WHERE " . db_create_in($option_id, 'option_id');
    \Ecdb::query($sql);
}